<!--
/**
@template: 见证资料签收表
@author: ChaoPengWang(wangcp-a@glodon.com)
@update: 2022/4/16 9:36 PM
-->
<template>
  <div class="layout-wrapper layout-witness">
    <div ref="demo" style="display: none"></div>
    <div class="layout-header layout-search">
      <el-form :inline="true" :model="searchForm" style="display:flex; flex-wrap: wrap; padding-right:10px">
        <el-form-item style="flex: 1; min-width: 140px">
          <el-button type="primary" @click="download">导出{{ isDownloading ? "中..." : "" }}</el-button>
          <el-button type="primary" @click="print" flex="1">打印</el-button>
        </el-form-item>

        <el-form-item label="业务部门">
          <el-select
            v-model="searchForm.businessUnit"
            class="ui-w200"
            option-max-width="200px"
            placeholder="请选择"
            multiple
            clearable
          >
            <el-option
              v-for="item in businessDepartmentOption"
              :key="item.label"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="见证人员">
          <el-select
            v-model="searchForm.witnessUserName"
            class="ui-w200"
            option-max-width="300px"
            placeholder="请选择"
            multiple
            clearable
          >
            <el-option
              v-for="item in witnessUserNameOption"
              :key="item.label"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="见证时间">
          <el-date-picker
            v-model="searchForm.witnessTime"
            class="ui-w260"
            unlink-panels
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="true"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
          />

        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="setTableData">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="layout-body">
      <el-table ref="taskTable" v-loading="tableLoading" :data="tableData" height="100%" stripe>
        <el-table-column type="index" align="left" label="序号" width="50">
          <template slot-scope="scope">
            {{ (pageObj.currentPage - 1) * pageObj.pageSize + 1 + scope.$index }}
          </template>
        </el-table-column>
        <el-table-column prop="projectName" label="项目名称" min-width="200" />
        <el-table-column prop="projectCode" label="项目序列号" min-width="200" />
        <el-table-column prop="witnessUserName" label="见证人员" min-width="100" />
        <el-table-column prop="businessUnit" label="部门名称" min-width="100" />
        <el-table-column prop="operateUserName" label="经办人员" min-width="100" />

        <el-table-column label="是否满足数据填报需要" min-width="140" />
        <el-table-column label="签收人" min-width="80" show-overflow-tooltip />
        <el-table-column label="签收日期" min-width="100" show-overflow-tooltip />
        <el-table-column label="备注" min-width="100" show-overflow-tooltip />
      </el-table>
    </div>
    <div class="layout-footer">
      <pagination
        v-if="pageObj.total > pageObj.pageSizes[0]"
        :total="pageObj.total"
        :page.sync="pageObj.currentPage"
        :limit.sync="pageObj.pageSize"
        :page-sizes="pageObj.pageSizes"
        @pagination="projectListFn()"
      />
    </div>
    <!-- 项目详情弹窗 -->
    <!-- <ProjectDetailsDialog :visible.sync="detailDialogShow" :projectId="currentProjectId" :taskObj="TASKOBJ" /> -->
    <!--    <ProjectDetailsDrawer-->
    <!--      :visible.sync="detailDialogShow"-->
    <!--      @closeDrawer="closeDrawerFn"-->
    <!--      :project-id="currentProjectId"-->
    <!--      :task-obj="TASKOBJ"-->
    <!--    />-->
  </div>
</template>
<script>
import ProjectDetailsDrawer from "../../../components/dialog/ProjectDetailsDrawer.vue";
import moment from "moment";
import { OnCalendar, signExcel, turnExcel, witnessRecordDistributeList } from "@/api/api";
import axios from "axios";
import _ from "lodash";
const data = moment().subtract(1, "day").format("YYYY-MM-DD");// 见证开始时间
export default {
  // 引入组件
  components: { ProjectDetailsDrawer },
  filters: {
    formatDateFn(data) {
      return moment(data).format("yyyy-MM-dd");
    }
  },
  computed: {
    managerFlag() {
      return (
        this.$store.getters.roleCode === "GDW_R_WITNESS_MANAGER" ||
        this.$store.getters.roleCode === "GDW_R_WITNESS_SUPER"
      );
    },
    username() {
      return this.$store.getters.username;
    }
  },
  props: {},
  data() {
    // [{
    //   value: 1,
    //   label: '东南',
    //   children: [{
    // 这里存放数据
    return {
      isDownloading: false,
      searchForm: {
        businessUnit: [], // 业务部门
        witnessUserName: [], // 见证人员
        witnessTime: [data, data]
      },
      businessDepartmentOption: [
        {
          label: "工程交易处",
          value: "工程交易处"
        }, {
          label: "采购交易处",
          value: "采购交易处"
        }, {
          label: "产权交易处",
          value: "产权交易处"
        }
      ], //业务部门选项
      witnessUserNameOption: [], // 见证人员选项
      tableData: [],
      tableLoading: false,
      pageObj: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        pageSizes: [10, 20, 30]
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      }
    };
  },
  created() {
    this.LLiet = ["全部"];
    this.getWitnessUserName();
  },
  watch: {
    searchForm: {
      deep: true,
      immediate: true,
      handler() {
        // 获取数据
        this.setTableData();
      }
    },
    "pageObj.currentPage"() {
      this.setTableData();
    },
    "pageObj.pageSize"() {
      this.setTableData();
    }
  },
  methods: {

    reset() {
      this.searchForm = {
        businessUnit: [], // 业务部门
        witnessUserName: [], // 见证人员
        witnessTime: [data, data]
      };
    },

    // 获取表格数据
    async setTableData() {
      try {
        this.tableLoading = true;
        const {
          searchForm: { businessUnit, witnessUserName, witnessTime },
          pageObj: { currentPage, pageSize }
        } = this;

        const params = {
          type: 2,
          businessUnitList: businessUnit,
          witnessUserNameList: witnessUserName,
          currentPage,
          pageSize
        };
        if (witnessTime && witnessTime.length === 2) {
          params.startTime = `${witnessTime[0]} 00:00:00`;
          params.endTime = `${witnessTime[1]} 23:59:59`;
        }

        const { code, data, message } = await witnessRecordDistributeList(params);
        if (code === 0) {
          this.tableData = data.result.map(({ data }) => {
            data.witnessUserName = data.bidSectionVOList[0].witnessSubTaskVOList.data[0].witnessUserName;
            delete data.bidSectionVOList;
            return data;
          });
          this.pageObj.total = data.pageBean.count;
        } else {
          this.$message.warning(message);
        }
      } catch (e) {
        console.error(e);
      } finally {
        this.tableLoading = false;
      }
    },

    // 获取见证人员
    async getWitnessUserName() {
      try {
        const { searchForm: { witnessTime } } = this;
        const { code, data, message } = await OnCalendar({
          endDate: "2022-10-01 00:00:00",
          startDate: "2022-09-01 00:00:00"
        });
        if (code === 0) {

          this.witnessUserNameOption = data.map(({ userName }) => ({
            label: userName,
            value: userName
          }));
        } else {
          this.$message.warning(message);
        }
      } catch (e) {
        console.error(e);
      }
    },

    projectListFn() {
    },

    download() {
      this.exportExcel();
    },

    async exportExcel() {
      try {
        if(this.isDownloading){
          return
        }
        this.isDownloading = true;
        const {
          searchForm: { businessUnit, witnessUserName, witnessTime },
          pageObj: { currentPage, pageSize }
        } = this;
        const params = {
          type: 2,
          businessUnitList: businessUnit,
          witnessUserNameList: witnessUserName,
          currentPage,
          pageSize
        };
        if (witnessTime && witnessTime.length === 2) {
          params.startTime = `${witnessTime[0]} 00:00:00`;
          params.endTime = `${witnessTime[1]} 23:59:59`;
        }
        const instance = axios.create({
          contentType: "application/json;charset=UTF-8",
          responseType: "blob"
        });

        const res = await instance.post("/gdw/gz/witness/export/signExcel", params);
        const fileName = "见证资料签收表.xlsx";
        const csvData = new Blob([res.data], { type: "application/xlsx" });
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(csvData, fileName);
        } else {
          const a = document.createElement("a");
          document.body.appendChild(a);
          a.style = "display: none";
          const url = window.URL.createObjectURL(csvData);
          a.href = url;
          a.download = fileName;
          a.click();
          a.remove();
          window.URL.revokeObjectURL(url);
        }

        let id = setTimeout(() => {
          clearTimeout(id);
          this.$message.success("导出成功");
        }, 100);

      } catch (e) {
        console.error(e);
      } finally {
        this.isDownloading = false;
      }
    },

    async print() {
      let tableData = [];
      const {
        searchForm: { businessUnit, witnessUserName, witnessTime },
        pageObj: { total }
      } = this;

      const params = {
        type: 2,
        businessUnitList: businessUnit,
        witnessUserNameList: witnessUserName,
        currentPage: 1,
        pageSize: total
      };
      if (witnessTime && witnessTime.length === 2) {
        params.startTime = `${witnessTime[0]} 00:00:00`;
        params.endTime = `${witnessTime[1]} 23:59:59`;
      }

      const { code, data, message } = await witnessRecordDistributeList(params);

      if (code === 0) {
        tableData = data.result.map(({ data }) => {
          data.witnessUserName = data.bidSectionVOList[0].witnessSubTaskVOList.data[0].witnessUserName;
          delete data.bidSectionVOList;
          return data;
        });
        let startTime = witnessTime && witnessTime[0] || "";
        let endTime = witnessTime && witnessTime[1] || "";

        let iframe = document.getElementById('iframeId');
        if(iframe){
          this.$refs.demo.removeChild(iframe);
        }
        iframe = document.createElement("iframe");
        iframe.id = "iframeId";

        iframe.onload = () => {
          const iframeBody = iframe.contentDocument || iframe.contentWindow.document;
          const html = `
 <div class="thead">
  <div class="e_title">
    <div>见证资料签收表</div>
  </div>
  <div class="e_note">
    <div>注：请各经办人签收前仔细检查资料是否满足数据填报的需要，如有资料缺漏，可直接联系项目见证人员，谢您的支持和理解！</div>
  </div>
  <div class="e_body">
    <div>填表人：</div>
    <div></div>
    <div>移交人：</div>
    <div></div>
    <div></div>
    <div></div>
    <div>见证日期：</div>
    <div>${startTime}</div>
    <div>至</div>
    <div>${endTime}</div>
  </div>
  <div class="e_body e_header">
        <div>序号</div>
        <div>项目名称</div>
        <div>项目序列号</div>
        <div>见证人员</div>
        <div>部门名称</div>
        <div>经办人</div>
        <div>是否满足数据填报需要</div>
        <div>签收人</div>
        <div>签收日期</div>
        <div>备注</div>
      </div>
  ${tableData.map((item, index) => {
            return `<div class="e_body">
        <div>${index + 1}</div>
        <div>${item.projectName}</div>
        <div>${item.projectCode}</div>
        <div>${item.witnessUserName}</div>
        <div>${item.businessUnit}</div>
        <div>${item.operateUserName}</div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
      </div>`;
          }).join("")}
</div>
<style>

.thead{
  font-weight: 400;
  font-size: 10px;
  text-align: left;
  border-top: 1px solid rgb(212,219,233);
  width: 100%;
}

.thead > div{
  border-bottom: 1px solid rgb(212,219,233);
  border-right: 1px solid rgb(212,219,233);
  width: 100%;
}

.thead > div > div{
  border-left: 1px solid rgb(212,219,233);
  padding: 5px 2px;
  word-break: break-all;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}

.e_title{
  font-size: 20px;
  font-weight: bold;
  line-height: 40px;
  height: 40px;
  text-align: center;
}
.e_note{
  font-size: 11px;
  color: red
}


.e_header{
  font-weight: bold;
  font-size: 11px;
  text-align: center;
}
.e_header > div{
  min-height: 40px;
}

.e_body{
  width: 100%;
  display: flex;
  justify-content: center;
  text-align: center;
}

.e_body> div:nth-child(1){
  width: 6%;
}
.e_body> div:nth-child(2){
  width: 18%;
}
.e_body> div:nth-child(3){
  width: 17%;
}
.e_body> div:nth-child(4){
  width: 8%;
}
.e_body> div:nth-child(5){
  width: 7%;
}
.e_body> div:nth-child(6){
  width: 7%;
}
.e_body> div:nth-child(7){
  width: 10%;
}
.e_body> div:nth-child(8){
  width: 9%;
}
.e_body> div:nth-child(9){
  width: 9%;
}
.e_body> div:nth-child(10){
  width: 9%;
}

</style>
`;
          iframeBody.body.innerHTML = html;
          iframe.contentWindow.print();
        }
        this.$refs.demo.appendChild(iframe);
      } else {
        this.$message.warning(message);
      }


      // const { searchForm, searchForm: { businessUnit, witnessUserName, witnessTime }, managerFlag, username } = this;
      // const params = {
      //   type: 2,
      //   businessUnit: businessUnit === "全部" ? "" : businessUnit,
      //   witnessUserName: managerFlag ? witnessUserName : username
      // };
      // if (witnessTime && witnessTime.length === 2) {
      //   params.startTime = `${witnessTime[0]} 00:00:00`;
      //   params.endTime = `${witnessTime[1]} 23:59:59`;
      // }
      // const instance = axios.create({
      //   timeout: 3000,
      //   contentType: "application/json;charset=UTF-8",
      //   responseType: "blob"
      // });
      //
      // const res = await instance.post("/gdw/gz/witness/export/signExcel", params);
      // const fileName = '见证资料签收表.xlsx';
      // const csvData = new Blob([res.data], { type: "application/xlsx" });
      // if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      //   window.navigator.msSaveOrOpenBlob(csvData, fileName);
      // } else {
      //   const ws = [];
      //   const workbook = await read(await csvData.arrayBuffer())
      //
      //   /* loop through the worksheet names in order */
      //   workbook.SheetNames.forEach(name => {
      //     /* generate HTML from the corresponding worksheets */
      //     const html = utils.sheet_to_html(workbook.Sheets[name]);
      //     var iframe = document.getElementById("printID");
      //     var iframedoc = iframe.contentDocument || iframe.contentWindow.document;
      //     console.log(this.$refs.taskTable.$el);
      //
      //     console.log(html);
      //     iframedoc.body.innerHTML = html;
      //
      //     //区分浏用的处理方法览器，选择调
      //     if(navigator.userAgent.toUpperCase().indexOf("TRIDENT")!=-1){
      //       //IE必须让iframe在页面展示，并且focus后才能打印
      //       document.getElementById("xxx").style.display = "block";
      //       //ie必须focus以后才能打印。
      //       window.frames["printID"].focus();
      //       //给机器一个20毫秒的等待时间。确保光标能够focus
      //       // setTimeout(iePrintcb,20,window.frames["printID"]);
      //     }else{
      //       iframe.contentWindow.print();
      //     }
      //
      //
      //
      //   });
      // }
    }
  }
};
</script>
<style lang="scss" scoped>

.witness-result {
  width: 76px;
  height: 20px;
  line-height: 20px;
  background: #fc9306;
  border-radius: 10px;
  color: #fff;
  font-size: 12px;
  text-align: center;
}

.rigthText {
  padding-right: 10px;
  float: right;
  // margin-left: 460px !important;
}
</style>
